package com.znjc.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.znjc.common.annotation.DataSource;
import com.znjc.common.enums.DataSourceType;
import com.znjc.device.domain.DevicePoint;
import com.znjc.device.domain.DeviceRuleRef;
import com.znjc.device.mapper.DevicePointMapper;
import com.znjc.device.service.IDevicePointService;
import com.znjc.device.service.IDeviceRuleRefService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author zengpc
 * @date 2023-12-04
 */
@Service
public class DevicePointServiceImpl extends ServiceImpl<DevicePointMapper, DevicePoint> implements IDevicePointService {

    @Resource
    private IDeviceRuleRefService deviceRuleRefService;

    @Override
    @DataSource(DataSourceType.MASTER)
    public String getPointName(Long id) {
        DevicePoint point = this.getById(id);
        if(null != point){
            return  point.getPointName();
        }
        return "";
    }

    @Override
    public Long getPointId(Long deviceId, String pointName) {
        LambdaQueryWrapper<DeviceRuleRef> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DeviceRuleRef::getDeviceId,deviceId);
        List<DeviceRuleRef> refs = deviceRuleRefService.list(queryWrapper);
        if(CollectionUtils.isNotEmpty(refs)){
            List<Long> pointIds = refs.stream().map(DeviceRuleRef::getPointId).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(pointIds)){
                LambdaQueryWrapper<DevicePoint> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(DevicePoint::getPointName,pointName);
                wrapper.eq(DevicePoint::getStatus,"0");
                wrapper.eq(DevicePoint::getDelFlag,"0");
                wrapper.in(DevicePoint::getId,pointIds);
                wrapper.last("limit 0,1");
                DevicePoint point = this.getOne(wrapper);
                if(null != point){
                    return point.getId();
                }
            }
        }
        return null;
    }

    @Override
    public List<DevicePoint> getListByTypeId(Long typeId) {
        LambdaQueryWrapper<DevicePoint> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DevicePoint::getStatus,"0");
        queryWrapper.eq(DevicePoint::getDelFlag,"0");
        queryWrapper.eq(DevicePoint::getTypeId,typeId);
        return  this.list(queryWrapper);
    }
}
